package com.easyaop.core.interceptor;

import com.easyaop.api.join.JoinImpl;
import com.easyaop.api.event.JoinManger;

import net.bytebuddy.asm.Advice;
import net.bytebuddy.implementation.bytecode.assign.Assigner;

public class EventAdvice {

    @Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class)
    public static boolean methodEnter(
            @Advice.Origin final Class clz

            , @Advice.Origin("#t\\##m#d") final String method
            , @Advice.AllArguments(readOnly = false,typing = Assigner.Typing.DYNAMIC)  Object[] allArguments
            , @Advice.This(optional = true) Object target
            , @Advice.Local("join") JoinImpl join) throws Exception {

        join = JoinImpl.of(clz, method, target, allArguments);
        JoinManger.enter(join);
//        System.out.println(11222);
        allArguments=join.getArguments();
//        allArguments=allArguments;
//        Object[] aaa=allArguments;
//        aaa[0]=null;
//        System.out.println("+sdddd"+allArguments[0]);
//        System.out.println("+sdddd"+join.getArguments()[0]);
//        allArguments=new Object[]{allArguments[0],allArguments[1]};
//        allArguments=new Object[]{null,"3"};
//        allArguments[0]=join.getArguments()[0];
        return join.isSkipOriginMethod();
    }

    @Advice.OnMethodExit(onThrowable = Throwable.class)
    public static void methodExit(
//            @Advice.Origin final Class clz
//            , @Advice.This(typing = Assigner.Typing.DYNAMIC) Object thisObject
            @Advice.Return(typing = Assigner.Typing.DYNAMIC, readOnly = false) Object returnValue
            , @Advice.Thrown(typing = Assigner.Typing.DYNAMIC) Throwable throwable
//            , @Advice.Enter Object[] enterObject
            , @Advice.Local("join") JoinImpl join) {
//        System.out.println(clz);
//         join = (JoinImpl) enterObject[1];
        if (throwable != null) {
            join.setThrowable(throwable);
            JoinManger.onThrows(join);
            return;
        }
        if (!join.isSkipOriginMethod()) {
            join.setReturnValue(returnValue);
        }
        JoinManger.exit(join);
        if (join.isChangReturn()) {
            returnValue = join.getReturnValue();
        }
    }
}
